//
//  THCPCFixVC.m
//  YJB
//
//  Created by 中电大维 on 2016/12/31.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THCPCPublishFixVC.h"
#import "THCPCObjectView.h"
#import "THCPCPublishCountVC.h"
#import "THTaskProtocolVC.h"
#import "THFixModel.h"
#import "THDescriptionModel.h"

#define FixView_Height 200

@interface THCPCPublishFixVC ()
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)NSMutableArray *fixs;
@property(nonatomic, strong)NSMutableDictionary *infoDict;
@property(nonatomic,strong)NSMutableArray *descriptions;
@end

@implementation THCPCPublishFixVC
{
    THCPCObjectView *_defaultView;
    UIView          *_opreationView;
    UIView          *_rateView;
    UIButton        *_addObjectUrlBtn;
    UIButton        *_delObjectUrlBtn;
    UIButton        *agreeButton;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUpNav];
    [self addSubView];
    self.descriptions = self.model.descriptions;
}
- (void)agreeClick:(UIButton *)button
{
    button.selected = !button.selected;
}
- (void)protocolClick:(UIButton *)button
{
    [self.navigationController pushViewController:[THTaskProtocolVC new] animated:YES];
}
- (void)publishTaskClick{
    
    [self.model.fixs removeAllObjects];
    if (self.descriptions.count != self.model.descriptions.count) {
        [self.descriptions removeLastObject];
    }
    
    for (THCPCObjectView *view in self.fixs) {
        THFixModel *model = [[THFixModel alloc] init];
        model.method = view.methodState;
        model.answer = view.answerField.text;
        model.require = view.answerRequireView.text;
        [self.model.fixs addObject:model];
    }
    if (!agreeButton.selected) {
        [MBProgressHUD showError:@"未同意协议，暂不能发布"];
        return;
    }
    [MBProgressHUD showMessage:@""];
    
    if (self.model.iconimage) {
        THDescriptionModel *mode = [[THDescriptionModel alloc] init];
        mode.image = self.model.iconimage;
        if (self.model.descriptions.count) {
            [self.model.descriptions insertObject:mode atIndex:0];
        }else{
            [self.model.descriptions addObject:mode];
        }
    }
    
    NSString *uploadUrl = THURL(@"upload_img.php");
    [YJNetworkTool uploadWithUrl:uploadUrl parameters:nil bodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        for (int i = 0; i < self.model.descriptions.count; i ++)
        {
            THDescriptionModel *model = self.model.descriptions[i];
            UIImage *selectImage = model.image;
            NSData *selectImageData = UIImageJPEGRepresentation(selectImage, 1.0);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *fileName = [NSString stringWithFormat:@"%@%d.png",[formatter stringFromDate:[NSDate date]],i];
            [formData appendPartWithFileData:selectImageData name:@"file[]" fileName:fileName mimeType:@"image/png"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nullable task, NSDictionary * _Nonnull responseObject) {
        MyLog(@"发布任务上传图片返回：%@",responseObject);
        [self publishContet:responseObject[@"return"][@"data"][@"img_list"]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        MyLog(@"上传失败 ======== %@",error);
    }];
    
}

- (void)publishContet:(NSMutableArray *)array
{
    
    NSMutableArray *descreptions = [[NSMutableArray alloc] init];
    NSMutableArray *fixs = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < self.model.descriptions.count; i++) {
        THDescriptionModel *mode = self.model.descriptions[i];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        if (self.model.iconimage) {
            
            if (array.count>i && [array[i] objectForKey:@"f"]) {
                [dict setObject:[array[i] objectForKey:@"img_url"] forKey:@"step_image"];
                [dict setObject:[NSString stringWithFormat:@"%@",mode.content] forKey:@"step_text"];
                [descreptions addObject:dict];
            }
            if (i == array.count-1) {
                self.model.adv_icon = [array[i] objectForKey:@"img_url"];
            }
        }else{
            if (array.count>i && [array[i] objectForKey:@"img_url"]) {
                [dict setObject:[array[i] objectForKey:@"img_url"] forKey:@"step_image"];
                [dict setObject:[NSString stringWithFormat:@"%@",mode.content] forKey:@"step_text"];
                [descreptions addObject:dict];
            }
        }
    }
    
    for (int i = 0; i < self.model.fixs.count; i++) {
        THFixModel *mode = self.model.fixs[i];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:[NSString stringWithFormat:@"%d",mode.method] forKey:@"ans_match"];
        [dict setObject:[NSString stringWithFormat:@"%@",mode.answer] forKey:@"ans_result"];
        [dict setObject:[NSString stringWithFormat:@"%@",mode.require] forKey:@"ans_request"];
        [fixs addObject:dict];
    }

    NSString *md5Key = [YJUserDefaultTool readKeyID];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"set_cpcclick_add";
    params[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
                            @"adv_title":self.model.title,
                            @"adv_url":self.model.url,
                            @"adv_icon":self.model.adv_icon,
                            @"total_num":self.model.totalgold,
                            @"gold_one":self.model.price,
                            @"oper_steps":descreptions,
                            @"set_answer":fixs,
                            @"user_info":[YJUserDefaultTool readUserName],
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key,
                            };
    
    [YJNetworkTool postWithUrl:THURL(@"cpcclick.php") parameters:params success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        if ([responseObject[@"return"][@"code"] integerValue] == 200)
        {
            [MBProgressHUD showSuccess:@"发布成功"];
        }else
        {
            NSString *message = responseObject[@"return"][@"message"];
            [MBProgressHUD showError:message toView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络不佳,稍后重试" toView:self.view];
    }];
}

- (void)cancelClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)objectUrlClick:(UIButton *)button
{
    if (button.tag == 1) {//添加新目标网址
        MyLog(@"添加新目标网址");
        
        if (self.fixs.count>=5) {
            [MBProgressHUD showError:@"最多添加5个匹配方式"];
            return;
        }
        
        THCPCObjectView *lastView = [self.fixs lastObject];
        THCPCObjectView *currentView = [[THCPCObjectView alloc] init];
        currentView.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:currentView];
        
        [currentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(lastView.mas_bottom);
            make.height.mas_equalTo(FixView_Height);
        }];
        [self.fixs addObject:currentView];
        [self setRemakeFrame:currentView];
    }else{//删除新目标网址
        
        MyLog(@"删除新目标网址");
        if (self.fixs.count == 1) {
            [MBProgressHUD showError:@"至少包含一个目标网址"];
            return;
        }
        THCPCObjectView *currentView = [self.fixs lastObject];
        [currentView removeFromSuperview];
        [self.fixs removeObject:currentView];
        
        currentView = [self.fixs lastObject];
        [self setRemakeFrame:currentView];
    }
}

- (void)setRemakeFrame:(THCPCObjectView *)currentView
{
    [_opreationView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(currentView.mas_bottom);
        make.left.mas_equalTo(0);
        make.right.equalTo(self.view.mas_right);
        make.height.mas_equalTo(100);
        //make.bottom.equalTo(self.scrollView.mas_bottom).offset(-15);
    }];
    [_rateView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_opreationView.mas_bottom);
        make.left.mas_equalTo(0);
        make.right.equalTo(self.view.mas_right);
        make.height.mas_equalTo(80);
        make.bottom.equalTo(self.scrollView.mas_bottom).offset(-15);
    }];
}


- (void)setUpNav{
    
    self.title = @"发布任务";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(publishTaskClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

- (void)addSubView
{
    _defaultView = [[THCPCObjectView alloc] init];
    [self.scrollView addSubview:_defaultView];
    [_defaultView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.scrollView.mas_top).offset(5);
        make.height.mas_equalTo(FixView_Height);
    }];
    [self.fixs addObject:_defaultView];
    
    _opreationView = [[UIView alloc] init];
    _opreationView.backgroundColor = [UIColor whiteColor];
    _opreationView.userInteractionEnabled = YES;
    [_scrollView addSubview:_opreationView];
    
    [self setOperationView];
    
    [_opreationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_defaultView.mas_bottom);
        make.left.mas_equalTo(0);
        make.right.equalTo(self.view.mas_right);
        make.height.mas_equalTo(100);
    }];
    
    _rateView = [[UIView alloc] init];
    [_scrollView addSubview:_rateView];
    [self setRateView];
    
    [_rateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_opreationView.mas_bottom);
        make.left.mas_equalTo(0);
        make.right.equalTo(self.view.mas_right);
        make.height.mas_equalTo(80);
        make.bottom.equalTo(self.scrollView.mas_bottom).offset(-15);
    }];
}
- (void)setRateView{
    NSString *rateStr = @"当前汇率：100金币=1元人民币";
    UILabel *rateLabel = [[UILabel alloc] init];
    rateLabel.font = FONT(14);
    rateLabel.textColor = [UIColor colorWithHexString:@"666666"];
    rateLabel.text = rateStr;
    [_rateView addSubview:rateLabel];
    [rateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.top.equalTo(_rateView.mas_top).offset(20);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(15);
    }];

    UIEdgeInsets insets = UIEdgeInsetsMake(0, 10, 0, 0);
    NSString *agreeStr = @"我已阅读并同意";
    CGFloat agreeWidth = [NSString widthForString:agreeStr fontSize:14 andHeight:15];
    
    agreeButton = [[UIButton alloc] init];
    [agreeButton setTitleColor:[UIColor colorWithHexString:@"999999"] forState:UIControlStateNormal];
    agreeButton.titleLabel.font = FONT(14);
    [agreeButton setTitleEdgeInsets:insets];
    [agreeButton setImage:Image(@"match_normal") forState:UIControlStateNormal];
    [agreeButton setImage:Image(@"match_selected") forState:UIControlStateSelected];
    [agreeButton setTitle:agreeStr forState:UIControlStateNormal];
    [_rateView addSubview:agreeButton];
    agreeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [agreeButton addTarget:self action:@selector(agreeClick:) forControlEvents:UIControlEventTouchUpInside];
    [agreeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(rateLabel.mas_bottom).offset(15);
        make.left.equalTo(rateLabel.mas_left);
        make.height.mas_equalTo(22);
        make.width.mas_equalTo(agreeWidth+32);
    }];
    NSString *protocolStr = @"《土豪任务管理协议》";
    //    CGFloat protocalWidth = [NSString widthForString:protocolStr fontSize:14 andHeight:15];
    UIButton *protocolButton = [[UIButton alloc] init];
    protocolButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [protocolButton setTitleColor:[UIColor colorWithHexString:@"0e41dc"] forState:UIControlStateNormal];
    protocolButton.titleLabel.font = FONT(14);
    [protocolButton setTitle:protocolStr forState:UIControlStateNormal];
    [_rateView addSubview:protocolButton];
    [protocolButton addTarget:self action:@selector(protocolClick:) forControlEvents:UIControlEventTouchUpInside];
    [protocolButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(agreeButton.mas_centerY);
        make.left.equalTo(agreeButton.mas_right);
        make.height.mas_equalTo(15);
        make.right.mas_equalTo(-12);
    }];

}

- (void)setOperationView
{
    _addObjectUrlBtn = [[UIButton alloc] init];
    _delObjectUrlBtn = [[UIButton alloc] init];
    UILabel *label = [[UILabel alloc] init];
    
    _addObjectUrlBtn.titleLabel.font = FONT(15);
    _delObjectUrlBtn.titleLabel.font = FONT(15);
    [_addObjectUrlBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_delObjectUrlBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_addObjectUrlBtn setBackgroundColor:[UIColor colorWithHexString:@"ff783c"]];
    [_delObjectUrlBtn setBackgroundColor:[UIColor colorWithHexString:@"dc462d"]];
    [_delObjectUrlBtn setBackgroundColor:[UIColor redColor]];
    
    [_addObjectUrlBtn.layer setMasksToBounds:YES];
    [_addObjectUrlBtn.layer setCornerRadius:3.0];
    [_delObjectUrlBtn.layer setMasksToBounds:YES];
    [_delObjectUrlBtn.layer setCornerRadius:3.0];
    
    [_addObjectUrlBtn setTitle:@"添加新目标网址" forState:UIControlStateNormal];
    [_delObjectUrlBtn setTitle:@"删除最后目标网址" forState:UIControlStateNormal];
    
    _addObjectUrlBtn.tag = 1;
    _delObjectUrlBtn.tag = 2;
    
    [_addObjectUrlBtn addTarget:self action:@selector(objectUrlClick:) forControlEvents:UIControlEventTouchUpInside];
    [_delObjectUrlBtn addTarget:self action:@selector(objectUrlClick:) forControlEvents:UIControlEventTouchUpInside];
    
    label.textColor = [UIColor colorWithHexString:@"333333"];
    label.font = FONT(12);
    label.text = @"为了防止用户作弊，请您提交多个目标网址与最终点击要求";
    
    [_opreationView addSubview:_addObjectUrlBtn];
    [_opreationView addSubview:_delObjectUrlBtn];
    [_opreationView addSubview:label];
    
    [_addObjectUrlBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.equalTo(_opreationView.mas_left).offset(12);
        make.right.equalTo(_opreationView.mas_centerX).offset(-20);
        make.height.mas_equalTo(40);
    }];
    [_delObjectUrlBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_addObjectUrlBtn.mas_top);
        make.left.equalTo(_opreationView.mas_centerX);
        make.right.equalTo(_opreationView.mas_right).offset(-12);
        make.height.equalTo(_addObjectUrlBtn.mas_height);
    }];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_addObjectUrlBtn.mas_bottom).offset(10);
        make.left.equalTo(_addObjectUrlBtn.mas_left);
        make.right.equalTo(_opreationView.mas_right).offset(-12);
        make.height.mas_equalTo(15);
    }];
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        //        _scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.userInteractionEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.backgroundColor = kUIColorFromRGB(0xeeeeee);
        // 是否反弹
        _scrollView.bounces = NO;
        [_scrollView flashScrollIndicators];
        [self.view addSubview:_scrollView];
        
        [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _scrollView;
}

- (NSMutableArray *)fixs
{
    if (!_fixs) {
        _fixs = [NSMutableArray array];
    }
    return _fixs;
}
- (NSMutableArray *)descriptions
{
    if (!_descriptions) {
        _descriptions = [[NSMutableArray alloc] init];
    }
    return _descriptions;
}

- (NSMutableDictionary *)infoDict
{
    if (!_infoDict) {
        _infoDict = [NSMutableDictionary dictionary];
    }
    return _infoDict;
}

@end
